package cn.jimmie.lib.qlog;

import java.util.concurrent.BlockingQueue;

/**
 * Func : 模仿Message, 可回收的日志类.
 * <p>
 * 避免不断的创建数据实体和Runnable
 *
 * <p> Create Time:  2019-12-18 12:42 </p>
 * <p> @author Jimmie.Qian  </p>
 */
final class RecyclerLog {
    private static final int MAX_POOL_SIZE = 10;
    private static final Object sPoolSync = new Object();
    private static RecyclerLog sPool;
    private static int sPoolSize = 0;
    private RecyclerLog next;

    String message;
    QLogLevel level;
    BlockingQueue<RecyclerLog> queue;

    Runnable callback = new Runnable() {
        @Override
        public void run() {
            if (message == null || level == null || queue == null) {
                recycle();
                return;
            }
            queue.offer(RecyclerLog.this);
            queue = null;
        }
    };

    static RecyclerLog obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                RecyclerLog m = sPool;
                sPool = m.next;
                m.next = null;
                sPoolSize--;
                return m;
            }
        }
        return new RecyclerLog();
    }

    void recycle() {
        message = null;
        level = null;
        queue = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
}
